var path = require('path');
var fs = require('fs');
var ROOT = path.join(__dirname, '../');
var F = path.join(ROOT, 'config.js');

module.exports = [
{
  url: '/',
  controller: async function (response) {
    response.render({});
  }
},

// apis
{
  url: '/api/config/:type',
  method: 'get',
  controller: async function (request, response) {
    this.body = JSON.parse(fs.readFileSync(F, 'utf8'))[this.params.type] || '[]';
  }
},
{
  url: '/api/config/:type',
  method: 'post',
  controller: async function (request, response) {
    var text = fs.readFileSync(F, 'utf8');
    var obj = JSON.parse(text);
    var arr = obj[this.params.type] || [];
    var body = await request.getBody();
    var item = arr[body.index];
    if (!item) {
      item = arr[body.index] = {};
    }
    item[body.key] = body.value;
    item.pattern = body.pattern;
    fs.writeFileSync(F, JSON.stringify(obj, null, 2));
    this.body = {status: 'success'}
  }
},
]
